var $j = jQuery;
var Loader = null;
var Decorator = null;
var jsLoader = null;
var jqGrid = null;

//Modules and associated functions
var modusers = null;
var modpatients = null;
var modsignals = null;
var modsettings = null;

function restartModule(id){
	if (id == 'modusers') return (modusers = new UserModule());
	if (id == 'modpatients') return (modpatients = new PatientModule());
	if (id == 'modsignals') return (modsignals = new SignalModule());
	return;
}

//Script Loader
function ScriptLoader(){return true;}
ScriptLoader.prototype.isLoaded = function(id){
	if (id == 'modusers') return (modusers != null);
	if (id == 'modpatients') return (modpatients != null);
	if (id == 'modsignals') return (modsignals != null);
	return;
};
ScriptLoader.prototype.load = function(id,urlscript){
	if(this.isLoaded(id)){
		restartModule(id);
	}else{
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.id = id;
		script.src = "http://127.0.0.1/diastole/"+ urlscript;
		document.body.appendChild(script);
	}
};

//Section Loader 
function SectionLoader(){	return true;}
SectionLoader.prototype.baseURL = "http://127.0.0.1/diastole/";
SectionLoader.prototype.load = function(relativeURL,divSection){
	var cURL = this.baseURL + relativeURL;
	$j.get(cURL,null,function(data){
		$j(divSection).html(data);
	});
};
SectionLoader.prototype.post = function(relativeURL,divSection,params){
	var cURL = this.baseURL + relativeURL;
	$j.post(cURL,params,function(data){
		$j(divSection).html(data);
	});
};

function getEntityId(href){
	//al hacer click modifique el anchor y que ahora figura en la url del browser
	var url = href.split("#");
	var entity = url[1]; //remuevo el numeral
	delete url;
	return entity;
}

// LinkDecorator class
function LinkDecorator(){	return true;}
LinkDecorator.prototype.decorateReq = function(links,hrefaction,targetDiv){
	$j(links).each(function(){
		$j(this).click(function(){
			var id = getEntityId(this.href);
			Loader.post(hrefaction,targetDiv,"id="+id);
		});
	});
};
LinkDecorator.prototype.decorate = function(links,targetDiv){
	$j(links).each(function(){
		$j(this).click(function(){
			var href = getEntityId(this.href);
			Loader.load(href,targetDiv);
		});
	});
};



$j(document).ready(function(){
	jsLoader = new ScriptLoader();
	Loader = new SectionLoader();
	Decorator = new LinkDecorator();
	Decorator.decorate("div#navigation li.section a","#content"); //starting up menu links
	
	//Top menu configuration
	$j("div#navigation li.section").hover(function(){
		$j(this).addClass("activesection");
	},
	function(){
		$j(this).removeClass("activesection");
	});
	
	
});

